<template>
	<view class="searchLayout">
		<view class="statusBar" :style="{height:statusBarHeight() + 'px'}"></view>
		<view class="search">
			<uni-search-bar @confirm="onSearch" @cancel="onCancel" @clear="onClear" focus placeholder="搜索"
				v-model="queryParams.name">
			</uni-search-bar>

		</view>


		<view v-if="!hasSearched">
			<view class="select">
				<button @click="select">选择搜索引擎:</button>
				<text>{{selection}}</text>
			</view>
			<view class="history" v-if="historySearch.length">
				<view class="topTitle">
					<view class="text">最近搜索</view>
					<view class="icon" @click="removeHistory">
						<uni-icons type="trash" size="25"></uni-icons>
					</view>
				</view>
				<view class="tabs">
					<view class="tab" v-for="tab in historySearch" :key="tab" @click="clickTab(tab)">{{tab}}</view>
				</view>
			</view>

			<view class="recommend">
				<view class="topTitle">
					<view class="text">热门搜索</view>
				</view>
				<view class="tabs">
					<view class="tab" v-for="tab in recommendList" :key="tab" @click="clickTab(tab)">{{tab}}</view>
				</view>
			</view>
		</view>

		<view class="hasSearch" v-if="hasSearched">
			<view class="topTitle">
				<view class="text">搜索结果</view>
			</view>
		</view>
		<view class="searchResult">
			<scroll-view scroll-y="true" style="height: 90vh;">


				<view class="noSearch" v-if="noSearch">
					<uv-empty mode="search" icon="http://cdn.uviewui.com/uview/empty/search.png"></uv-empty>
				</view>
				<view class="hasSearch" v-else>
					<course v-if="isLocal" @touchstart="gtouchstartLocal(course)" @touchmove="handleTouchMove"
						@touchend="gtouchEndLocal(course.courseId)" v-for="course in courseList" :key="course.courseId"
						:courseInfo="course"></course>
					<courseExternal v-else @touchstart="gtouchstartExternal(item)" @touchmove="handleTouchMove"
						@touchend="gtouchEndExternal()" v-for="(item,index) in courseList" :key="index"
						:title="item.title" :pic="item.pic" :link="item.link"></courseExternal>
				</view>
			</scroll-view>
		</view>

		<!-- 课程简介弹出框 -->
		<uni-popup ref="coursepopupLocal" type="bottom" v-if="isLocal">
			<view class="coursepop">
				<view class="header">
					<view></view>
					<view class="title">
						课程快速入门
					</view>
					<view class="close" @click="closer">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y="true">
					<view class="content">
						<text class="lessons_title">授课时长<br /><br /></text>
						<text class="lessons_content">{{courseIntroduceInfo.classHour}}<br /><br /></text>
						<text class="lessons_title">课程介绍<br /><br /></text>
						<text class="lessons_content">{{courseIntroduceInfo.courseIntroduction}}<br /><br /></text>
						<text class="lessons_title">课程重难点</text>
						<markdown :markdown="courseIntroduceInfo.keyAndDifficultPoints"></markdown>
					</view>
				</scroll-view>
			</view>
		</uni-popup>

		<!-- 课程简介弹出框 -->
		<uni-popup ref="coursepopupExternal" type="bottom" v-else>
			<view class="coursepop">
				<view class="header">
					<view></view>
					<view class="title">
						课程快速入门
					</view>
					<view class="close" @click="closer">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y="true">
					<view class="content">
						<text class="lessons_title">课程标题<br /><br /></text>
						<text class="lessons_content">{{courseIntroduceInfo.title}}<br /><br /></text>
						<text class="lessons_title">课程描述<br /><br /></text>
						<text class="lessons_content">{{courseIntroduceInfo.desc}}<br /><br /></text>
					</view>
				</scroll-view>
			</view>
		</uni-popup>

	</view>
</template>

<script setup>
	import {
		ref
	} from "vue"
	import {
		onLoad,
		onUnload,
		onReachBottom
	} from "@dcloudio/uni-app"
	import {
		statusBarHeight
	} from "../../utils/system.js"
	import apis from "../../api/apis.js"

	// 课程简介的信息  
	const courseIntroduceInfo = ref({})

	// 是否长按的变量记录
	const isLongPress = ref(false);

	//长按事件（起始）
	let timeOutEvent;
	const gtouchstartLocal = (course) => {
		// startX = event.touches[0].clientX;
		// startY = event.touches[0].clientY;
		// console.log(course)
		courseIntroduceInfo.value.classHour = course.classHour;
		courseIntroduceInfo.value.courseIntroduction = course.courseIntroduction;
		courseIntroduceInfo.value.keyAndDifficultPoints = course.keyAndDifficultPoints;
		console.log(courseIntroduceInfo.value);
		timeOutEvent = setTimeout(() => {
			isLongPress.value = true;
			// console.log(123414123)
			courseIntroduce();
		}, 500); //这里设置定时器，定义长按500毫秒触发长按事件
	}

	const gtouchstartExternal = (course) => {
		// startX = event.touches[0].clientX;
		// startY = event.touches[0].clientY;
		// console.log(course)
		courseIntroduceInfo.value = course;
		console.log(courseIntroduceInfo.value);
		timeOutEvent = setTimeout(() => {
			isLongPress.value = true;
			// console.log(123414123)
			courseIntroduce();
		}, 500); //这里设置定时器，定义长按500毫秒触发长按事件
	}
	//手释放，如果在500毫秒内就释放，则取消长按事件，此时可以执行onclick应该执行的事件


	const gtouchEndLocal = (id) => {
		clearTimeout(timeOutEvent); //清除定时器
		// console.log(timeOutEvent)
		if (timeOutEvent != 0 && !isLongPress.value) {
			// console.log("点击")
			if (Math.abs(movedX) > 20 || Math.abs(movedY) > 20) {
				// console.log('滑动');
				movedX = 0;
				movedY = 0;
			} else {
				uni.navigateTo({
					url: "/pages/video/video?id=" + id
				})
			}

		}
		isLongPress.value = false;

	}
	const gtouchEndExternal = () => {
		clearTimeout(timeOutEvent); //清除定时器
		// console.log(timeOutEvent)
		if (timeOutEvent != 0 && !isLongPress.value) {
			// console.log("点击")
			if (Math.abs(movedX) > 20 || Math.abs(movedY) > 20) {
				// console.log('滑动');
				movedX = 0;
				movedY = 0;
			} else {
				// uni.navigateTo({
				// 	url: "/pages/video/video?id=" + id
				// })
				console.log("外部跳转")
			}

		}
		isLongPress.value = false;

	}


	let movedX = 0; // 移动的x坐标距离
	let movedY = 0; // 移动的y坐标距离


	const handleTouchMove = (event) => {
		movedX = event.touches[0].clientX;
		movedY = event.touches[0].clientY;

		// 清除定时器，防止滑动过程中触发长按
		clearTimeout(timeOutEvent);
		timeOutEvent = null;
	};

	const coursepopupLocal = ref(null)
	const coursepopupExternal = ref(null)
	// 课程简洁弹出框
	const courseIntroduce = () => {
		if (isLocal.value) {
			coursepopupLocal.value.open()
			return
		}
		coursepopupExternal.value.open()
	}
	// 关闭底部弹出框
	const closer = () => {
		// 不能放到一块 ,因为打开外部资源弹出框时,本地资源弹出框是没有开启的,所以汇报close未定义
		// coursepopupLocal.value.close()
		if (isLocal.value) {
			coursepopupLocal.value.close()
			return
		}

		coursepopupExternal.value.close()
	}

	const arr = ['本站', '哔站']
	const isLocal = ref(true)
	const selection = ref('本站')
	//课程列表 本地
	const courseList = ref([])
	// 外部资源
	// const externalResources = ref([])  直接共用一个courseList了
	function select() {
		uni.showActionSheet({
			title: "请选择",
			itemList: arr,
			success(res) {
				selection.value = arr[res.tapIndex]

			}
		})
	}
	//查询参数
	const queryParams = ref({
		name: ""
	})

	//搜索历史词
	const historySearch = ref(uni.getStorageSync("historySearch") || [])

	//热门搜索词
	const recommendList = ref(["Java", "UI设计", "Python", "VR/AR"])

	//没有更多
	const noData = ref(false)
	//没有搜索结果
	const noSearch = ref(false)
	const hasSearched = ref(false)
	//搜索tag隐藏
	// const disSearch = ref(false)
	//搜索结果列表


	//点击搜索
	const onSearch = () => {
		//搜索历史内容 用new Set展开得到一个新的不重复的集合
		if (queryParams.value.name.trim()) {
			historySearch.value = [...new Set([queryParams.value.name, ...historySearch.value])]
			uni.setStorageSync("historySearch", historySearch.value)
			if (selection.value == '哔站') {

				isLocal.value = false
				searchDateOutside()
			} else {

				isLocal.value = true
				searchData()
			}
			hasSearched.value = true
		}
		// disSearch.value = true
	}

	//点击清除按钮
	const onClear = () => {
		noSearch.value = false
		hasSearched.value = false
		courseList.value = []
	}
	//点击取消返回上页
	const onCancel = () => {
		uni.navigateBack()
	}


	//点击标签进行搜索
	const clickTab = (value) => {
		queryParams.value.name = value
		onSearch()
	}

	//点击清空搜索记录
	const removeHistory = () => {
		uni.showModal({
			title: "是否清空历史搜索？",
			success: res => {
				if (res.confirm) {
					uni.removeStorageSync("historySearch")
					historySearch.value = []
				}
			}
		})
	}

	const searchData = async () => {

		let res = await apis.getSearchCourse(queryParams.value.name).then(res => {
			// console.log("内部课程：",res.data)
			courseList.value = res.data || null
			// console.log("courseList:",courseList.value)
			if (!res.data) noSearch.value = true
			else noSearch.value = false
		}).catch(error => {
			noSearch.value = true
		})

		// console.log(courseList.value)
	}

	const searchDateOutside = async () => {
		let res = await apis.searchExternal(queryParams.value.name)
		// console.log("外部课程：",res.data)
		courseList.value = res.data || null
		// console.log("courseList:",courseList.value)
		if (!res.data) noSearch.value = true
		else noSearch.value = false
	}
</script>

<style lang="scss" scoped>
	.searchLayout {
		.search {
			padding: 0 10rpx;
		}

		.select {
			width: 40vw;
			padding: 0 20rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;

			button {
				width: 50vw;
				padding: 0;
				margin-right: 20rpx;
				font-size: 20rpx;
				border-radius: 10rpx;
				background-color: rgba(22, 93, 255, 1);
				color: white;
			}

			text {
				width: 20vw;
				font-size: 20rpx;
			}
		}

		.topTitle {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 32rpx;
			color: #83cbff;
		}

		.history {
			padding: 30rpx;
		}

		.recommend {
			padding: 30rpx;
		}

		.tabs {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			padding-top: 20rpx;

			.tab {
				background: #F4F4F4;
				font-size: 28rpx;
				color: #333;
				padding: 10rpx 28rpx;
				border-radius: 50rpx;
				margin-right: 20rpx;
				margin-top: 20rpx;
			}
		}

		.list {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 5rpx;
			padding: 20rpx 5rpx;

			.item {
				height: 440rpx;

				image {
					width: 100%;
					height: 100%;
					display: block;
				}
			}
		}

		.noSearch {
			padding: 30rpx;

			.title {
				margin-bottom: 30rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 32rpx;
				color: #83cbff;
			}

		}

		.hasSearch {
			padding-left: 30rpx;
			padding-top: 30rpx;
		}

		.searchResult {
			padding-top: 15rpx;
		}

		.coursepop {
			background-color: #fff;
			padding: 30rpx;
			border-radius: 30rpx 30rpx 0 0;
			overflow: hidden;

			.header {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.title {
					color: black;
					font-size: 30rpx;
					font-weight: 600;
					// padding-left: 6rpx;
				}

				.close {
					padding: 6rpx;
				}
			}

			.lessons_title {
				font-size: 33rpx;
				font-weight: 700;
				padding: 20rpx 0rpx;
			}

			scroll-view {
				max-height: 50vh;

				.content {
					// display: flex;
					padding: 16rpx 0;
					font-size: 32rpx;
					line-height: 1.7em;

					.ask {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 10rpx;

						input {
							border: 1rpx solid #636263;
							width: 70%;
							padding: 10rpx;
						}

						button {
							background-color: #33A3DC;
							color: white;
						}
					}
				}
			}
		}
	}
</style>